package com.itbbfx.controller;

import com.itbbfx.config.UserCredentialsMatcher;
import com.itbbfx.entity.User;
import com.itbbfx.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/toUpdateLogin")
    public String toUpdateLogin(Model model,Integer userid){
        model.addAttribute("usersLogin", userService.queryUser(userid));
        return "systemManager/user/updateLogin";
    }

    @ResponseBody
    @RequestMapping("/editLogin")
    public int editLogin(User user){
        return userService.updateLoginUser(user);
    }

    @ResponseBody
    @RequestMapping("/editPwd")
    public Object editPwd(User user, String loginname,String pwd,String pwd1){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();

        try{
            subject.login(token);
            String salt = UserCredentialsMatcher.generateSalt(6);

            //MD5加密迭代两次
            user.setPwd(UserCredentialsMatcher.encryptPassword("md5",pwd1,salt,2));
            user.setSalt(salt);
            userService.editPwd(user);
            return "1"; // 修改成功
        } catch (IncorrectCredentialsException e) {
            return "0";//密码错误
        }

    }
}